package com.yueban.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.image.SmartImageView;
import com.yueban.R;
import com.yueban.activity.JoinActivity;
import com.yueban.activity.PersonalInfoActivity;
import com.yueban.constant.HttpConstant;
import com.yueban.model.ActivityData;
import com.yueban.model.BaseResponse;
import com.yueban.model.Comment;
import com.yueban.model.DataHolder;
import com.yueban.model.ResultCode;
import com.yueban.net.NetWorkController;
import com.yueban.util.DialogUtil;
import com.yueban.util.Dp2Px;
import com.yueban.util.ListViewHeightUtil;
import com.yueban.util.SPManager;
import com.yueban.views.NoScrollGridView;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by guan on 17-8-1.
 */

public class HomeActivitiesListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private DataHolder dataHolder;
    private Context context;
    private SPManager spManager;

    public HomeActivitiesListAdapter(DataHolder dataHolder) {
        this.dataHolder = dataHolder;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.context = parent.getContext();
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        return new CardViewHolder(layoutInflater.inflate(R.layout.item_home_content, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final CardViewHolder viewHolder = (CardViewHolder) holder;
        final ActivityData activityData = dataHolder.getActivityDatas().get(position);
        viewHolder.content.setText(activityData.getContent());
        viewHolder.address.setText(activityData.getAddress());
        viewHolder.uName.setText(activityData.getUserName());
        //显示发布者头像
        viewHolder.uIcon.setImageUrl(HttpConstant.SERVER_URL + HttpConstant.GET_USER_ICON
                + "?userId=" + activityData.getUserId());

        //显示发布日期
        Date date = activityData.getDate();
        if (date != null) {
            String formatDate = DateFormat.getDateInstance(DateFormat.FULL).format(date);
            viewHolder.dateShow.setText(formatDate);
        } else
            viewHolder.dateShow.setText("");

        //加载配图
        HomePictureGridAdapter pictureGridAdapter = new HomePictureGridAdapter(context, activityData.getImageNames());
        ConstraintLayout.LayoutParams linearParams =
                (ConstraintLayout.LayoutParams) viewHolder.pictureGrid.getLayoutParams();
        //如果图片大于三张则显示两行
        if (activityData.getImageNames().size() < 1) {
            linearParams.height = Dp2Px.dp2px(context, 0);
        } else if (activityData.getImageNames().size() < 4) {
            linearParams.height = Dp2Px.dp2px(context, 116);
        } else if (activityData.getImageNames().size() < 7) {
            linearParams.height = Dp2Px.dp2px(context, 235);
        } else if (activityData.getImageNames().size() < 10) {
            linearParams.height = Dp2Px.dp2px(context, 116 * 3 + 3 * 2);
        }
        viewHolder.pictureGrid.setLayoutParams(linearParams);
        viewHolder.pictureGrid.setAdapter(pictureGridAdapter);

        //加载评论
        List<Comment> comments = activityData.getComments();
        if (comments == null)
            comments = new ArrayList<>();
        final HomeCommentListAdapter commentListAdapter = new HomeCommentListAdapter(context, comments);
        viewHolder.commentList.setAdapter(commentListAdapter);
        //调整显示评论的listView的高度
        ListViewHeightUtil.setListViewHeightBasedOnChildren(viewHolder.commentList);
        //显示评论数
        int commentNum = comments.size();
        if (commentNum > 99) {
            viewHolder.commentNum.setText("(" + 99 + "+)");
        } else {
            viewHolder.commentNum.setText("(" + commentNum + ")");
        }

        //显示参与人数
        viewHolder.joinNum.setText("(" + activityData.getJoinNum() + ")");

        //点击发布者姓名和头像的事件监听器
        View.OnClickListener icon_name_listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, PersonalInfoActivity.class);
                intent.putExtra("userId", activityData.getUserId());
                context.startActivity(intent);
            }
        };
        viewHolder.uIcon.setOnClickListener(icon_name_listener);
        viewHolder.uName.setOnClickListener(icon_name_listener);
        //评论按钮监听器
        View.OnClickListener commentClick = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final EditText editText = new EditText(context);

                DialogUtil.showInputDialog(context, "评论", editText, "提交", "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String comment = editText.getText().toString().trim();
                        if ("".equals(comment))
                            return;
                        submitComment(comment, activityData.getId(),
                                viewHolder.commentList, viewHolder.commentNum);
                    }
                }, null);
            }
        };
        viewHolder.commentNum.setOnClickListener(commentClick);
        viewHolder.commentText.setOnClickListener(commentClick);
        //点击参与监听器
        View.OnClickListener joinClick = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, JoinActivity.class);
                intent.putExtra("activityId", activityData.getId());
                context.startActivity(intent);
            }
        };
        viewHolder.joinText.setOnClickListener(joinClick);
        viewHolder.joinNum.setOnClickListener(joinClick);

    }

    //向服务器提交评论
    private void submitComment(final String commentText, long activityId,
                               final ListView commentList, final TextView textView) {
        spManager = new SPManager(context);
        NetWorkController netWorkController = new NetWorkController();
        netWorkController.submitComment(activityId, spManager.getUserId(),
                commentText).subscribe(new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull BaseResponse baseResponse) {
                if (baseResponse.getStatus() == ResultCode.SUCCESS) {
                    //如果提交成功，不刷新，本地添加评论
                    Comment mComment = new Comment();
                    mComment.setUserId(spManager.getUserId());
                    mComment.setUserName(spManager.getUserName());
                    mComment.setCommentText(commentText);

                    HomeCommentListAdapter adapter = (HomeCommentListAdapter) commentList.getAdapter();
                    List<Comment> comments = adapter.getComments();
                    comments.add(mComment);
                    ListViewHeightUtil.setListViewHeightBasedOnChildren(commentList);
                    adapter.notifyDataSetChanged();
                    textView.setText("(" + comments.size() + ")");
                } else {
                    Toast.makeText(context, baseResponse.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(@NonNull Throwable e) {
                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public int getItemCount() {
        if (dataHolder.getActivityDatas() != null)
            return dataHolder.getActivityDatas().size();
        else
            return 0;
    }

    private class CardViewHolder extends RecyclerView.ViewHolder {
        private SmartImageView uIcon;
        private TextView uName;
        private TextView dateShow;
        private TextView content;
        private TextView address;
        private TextView joinText;
        private TextView joinNum;
        private TextView commentText;
        private TextView commentNum;
        private NoScrollGridView pictureGrid;
        private ListView commentList;

        private CardViewHolder(View view) {
            super(view);
            uIcon = (SmartImageView) view.findViewById(R.id.uIcon);
            uName = (TextView) view.findViewById(R.id.uName);
            dateShow = (TextView) view.findViewById(R.id.dateShow);
            content = (TextView) view.findViewById(R.id.activityContent);
            address = (TextView) view.findViewById(R.id.addressShow);
            joinText = (TextView) view.findViewById(R.id.joinText);
            joinNum = (TextView) view.findViewById(R.id.joinNumText);
            commentText = (TextView) view.findViewById(R.id.commentText);
            commentNum = (TextView) view.findViewById(R.id.commentNum);
            pictureGrid = (NoScrollGridView) view.findViewById(R.id.pictureGrid);
            commentList = (ListView) view.findViewById(R.id.commentList);

        }
    }

}
